package com.jxt.myjxtmanager.manager;

import com.jxt.myjxtmanager.utils.LogUtils.LogInfo;

import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;

/**
 * 事件管理 ， 实时刷新
 *
 * @author Administrator
 */
public class Cache {


	public final static int SHARED_MESSAGE = 0X123;
	public final static int MESSAGE_NOTE = 0X124;
	public final static int MESSAGE_WX_BIND = 0X125;
	

	/**
	 * 侦听者集合，采用弱引用模式，不影响垃圾回收
	 */
	private static volatile List<WeakReference<EventListener>> listenerList = new LinkedList<WeakReference<EventListener>>();

	/**
	 * 添加被监听者
	 */
	public static void put(EventListener instance) {
		for (WeakReference<EventListener> reference : listenerList) {
			if (null == reference || reference.get() == null) {
				continue;
			}
			if (reference.get().hashCode() == instance.hashCode()) {
				return;
			}
		}
		listenerList.add(new WeakReference<EventListener>(instance));
	}

	/**
	 * 移除被监听者
	 */
	public static void remove(EventListener instance) {
		for (WeakReference<EventListener> reference : listenerList) {
			if (null == reference || reference.get() == null) {
				continue;
			}
			if (reference.get().hashCode() == instance.hashCode()) {
				listenerList.remove(reference.get());
				return;
			}
		}
	}

	/**
	 * 通知所有侦听着
	 */
	public static void notifyChanged(int status,int unReadMessage) {
		if (listenerList.isEmpty()) {
			LogInfo.i("getMessageInfos", "notifyChanged: listenerList is null");
			return;
		}
		WeakReference<EventListener> reference = null;
		for (int i = 0; i < listenerList.size(); i++) {
			reference = listenerList.get(i);
			EventListener l = reference.get();
			if (l == null) {
				// 对象已经被垃圾回收，则从list中移除该侦听者
				listenerList.remove(i);
			} else {
				// 通知该侦听者
				LogInfo.i("getMessageInfos", "notifyChanged: listenerList l");
				l.onMessageNotification(l.getMessageNotification(), status,unReadMessage);
			}
		}
	}
}
